package com.yenlien.traceyun.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.service.QiniuService;
import com.yenlien.traceyun.business.service.rest.usercenter.FileRestService;
import com.yenlien.traceyun.common.utils.FileUtil;
import com.yenlien.traceyun.common.utils.HttpUtil;
import com.yenlien.traceyun.common.utils.RandomUtil;
import com.yenlien.traceyun.webase.controller.BaseController;
import com.yenlien.traceyun.webase.exception.BusinessException;
import com.yenlien.traceyun.webase.exception.ErrorPageException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-03-12
 * @description:文件上传
 **/
@Controller
public class FileController extends BaseController {

    public static final String ROOT = "upload";

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private QiniuService qiniuService;

    @Autowired
    private FileRestService fileRestService;


    /**
     * 七牛多文件上传
     *
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "file/qiniu/upload")
    public Object qiniuUpload(HttpServletRequest request) throws IOException {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
        List<String> names = new ArrayList<>();
        if (files != null) {
            for (int i = 0; i < files.size(); i++) {
                MultipartFile file = files.get(i);
                String name = qiniuService.upload(file.getInputStream(), file.getOriginalFilename());
                names.add(name);
            }
        }
        return names;
    }

    /**
     * 七牛下载
     *
     * @param filename
     * @param response
     * @throws ErrorPageException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "file/qiniu/{filename:.+}")
    public void qiniuLoadFile(@PathVariable("filename") String filename, HttpServletResponse response) throws ErrorPageException, IOException {
        String suf = FileUtil.getSuffix(filename);
        if (suf.contains("png") || suf.contains("jpg") || suf.contains("gif") || suf.contains("JPEG")) {
            response.setContentType("image/png");
        } else {
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        }
        byte[] bytes = HttpUtil.getFile(qiniuService.download(filename));
        if (bytes == null) {
            throw new ErrorPageException("【" + filename + "】 is not exist");
        }
        response.getOutputStream().write(bytes);
    }

    //上传用户中心
    @ResponseBody
    @RequestMapping(value = "/file/upload")
    public Object uploadCenter(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
        String fileName = fileRestService.upload(files);
        JSONObject obj = new JSONObject();
        obj.put("fileName", fileName);
        return success(obj);
    }

    //从用户中心下载
    @ResponseBody
    @RequestMapping(value = "/file/show/{filename:.+}")
    public void showCenter(@PathVariable("filename") String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.getOutputStream().write(fileRestService.show(filename, request.getParameter("ys")));
    }

    @ResponseBody
    @RequestMapping(value = "/file/delete/{filename}")
    public Object delete(@PathVariable("filename") String filename, HttpServletRequest request, HttpServletResponse response) throws IOException, ErrorPageException {
        fileRestService.delete(filename);
        return success("success");
    }

    //多文件上传
//    @ResponseBody
//    @RequestMapping(value = "file/upload")
    public Object saveQueryFileDatas(HttpServletRequest request) throws IllegalStateException, IOException {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
        StringBuilder sbAddress = new StringBuilder();
        StringBuilder fnames = new StringBuilder();
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/file/show/";
        File destFile = new File(Paths.get(ROOT).toAbsolutePath().toString());

        if (!destFile.exists()) {
            destFile.mkdirs();
        }
        if (files != null) {
            for (int i = 0; i < files.size(); i++) {
                String type = files.get(i).getOriginalFilename().substring(
                        files.get(i).getOriginalFilename().indexOf("."));// 取文件格式后缀名

                String filename = System.currentTimeMillis() + "_" + RandomUtil.random(6) + type;// 取当前时间戳作为文件名
                File sourceFile = new File(Paths.get(ROOT, filename).toAbsolutePath().toString());
                files.get(i).transferTo(sourceFile);
                sbAddress.append(basePath).append(filename).append(";");
                fnames.append(filename).append(";");
            }
        }
        JSONObject result = new JSONObject();

        if (sbAddress.length() > 0 && fnames.length() > 0) {
            result.put("url", sbAddress.substring(0, sbAddress.length() - 1));
            result.put("name", fnames.substring(0, fnames.length() - 1));
            return result;
        }

        throw new BusinessException("5000", "路径和文件名错误");
    }

    //    @ResponseBody
//    @RequestMapping(value = "file/show/{filename:.+}")
    public void loadFile(@PathVariable("filename") String filename, HttpServletResponse response) throws IOException, ErrorPageException {
        BufferedInputStream in = null;
        ByteArrayOutputStream bos = null;
        try {
            File file = resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()).getFile();
            bos = new ByteArrayOutputStream();
            String suf = FileUtil.getSuffix(filename);
            in = new BufferedInputStream(new FileInputStream(file));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            if (suf.contains("png") || suf.contains("jpg") || suf.contains("gif") || suf.contains("JPEG")) {
                response.setContentType("image/png");
            } else {
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            }
            response.getOutputStream().write(bos.toByteArray());
        } catch (IOException e) {
            throw new ErrorPageException("文件【" + filename + "】不存在");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
